<template>
	<view class="container">
		<view class="banner">
			<swiper class="swiper" circular :indicator-dots="false" :autoplay="false" :current="current" @change="swiperChange">
				<swiper-item v-for="(item, index) in blist" :key="index">
					<view class="swiper-item" v-if="item.type == 'video'">
						<video :src="http + item.url" object-fit="fill"></video>
					</view>
					<view class="swiper-item" v-else>
						<image :src="http + item.url" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="banner-bottom">
			<scroll-view class="scroll-view_H" scroll-x="true">
				<view class="item" :class="{ on: current == index }" v-for="(item, index) in blist" :key="index" @click="scrollChange(index)">
					<image :src="http + item.url + '?x-oss-process=video/snapshot,w_0,h_0,t_0,f_jpg,m_fast,ar_auto'" mode="aspectFill" v-if="item.type == 'video'"></image>
					<image :src="http + item.url" mode="aspectFill" v-else></image>
				</view>
			</scroll-view>
		</view>
		<view class="mian">
			<view class="title-price u-flex u-col-center u-row-between">
				<view class="l">
					{{ data.title }}
				</view>
				<view class="r">{{ data.sales_price }}元</view>
			</view>
			<view class="tips">
				<text v-for="(item2, index2) in data.label_arr" :key="index2">{{ item2 }}</text>
			</view>
		</view>
		<view class="mian">
			<view class="title">游戏说明</view>
			<view class="body">
				<u-parse :content="content1"></u-parse>
			</view>
		</view>
		<view class="mian">
			<view class="title">回收说明</view>
			<view class="body">
				<u-parse :content="content2"></u-parse>
			</view>
		</view>
		<view class="footer u-flex u-col-center u-row-between">
			<view class="l u-flex u-col-center">
				<contact-button tnt-inst-id="iA3_QVo5" scene="SCE01262333" size="20" color="#333" icon="/static/image/kf.png" />
				<!-- <image src="." mode="aspectFill"></image> -->
				<image src="../../static/image/fx.png" mode="aspectFill" @click="showSharePanel"></image>
			</view>
			<view class="r" @click="open" style="margin-right: 30rpx">购买</view>
			<view class="r" @click="open">卖出</view>
		</view>
		<u-popup :show="show" :round="10" mode="bottom" closeable @close="close" @open="open">
			<view class="pop-buy">
				<view class="title">
					{{ data.title }}
				</view>
				<view class="list">
					<scroll-view scroll-y="true" class="scroll-Y">
						<view class="item" v-for="(item, index) in specList" :key="index">
							<view class="t">
								{{ item.name }}
							</view>
							<view class="c u-flex u-col-center u-row-between">
								<view
									class="i"
									:class="{ on: index2 == item.sindex }"
									v-for="(item2, index2) in item.child"
									:key="index2"
									@click="navChange(item, index, item2, index2)"
								>
									{{ item2 }}
								</view>
							</view>
						</view>
						<view class="item" v-if="data.mountings">
							<view class="t">请选择带配件情况（多选）必选：</view>
							<view class="c u-flex u-col-center u-row-between">
								<view class="i" :class="item.active ? 'on' : ''" v-for="(item, index) in data.mountings" @click="changMountings(item)">
									{{ item.title }}
								</view>
							</view>
						</view>
						<view class="item">
							<view class="t">选择验货服务费</view>
							<view class="c u-flex u-col-center u-row-between">
								<view class="i" :class="{ on: type == 1 }" @click="changeType(1)">在我家买的-{{ price1 }}元</view>
								<view v-if="data.is_receive_other == 1" class="i" :class="{ on: type == 2 }" @click="changeType(2)">在别人家买的-{{ price2 }}元</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="total">
					预计可获得
					<text>{{ total(specList, specTableList, type) }}</text>
					元
				</view>
				<view class="btn" @click="submit">加入回收袋</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			type: 1, // 验货服务费类型：1-自家购买 2-别家购买
			show: false, // 弹窗显示状态
			blist: [], // 轮播图/视频列表
			http: this.$imgUrl, // 图片基础路径
			content1: '', // 游戏说明内容
			content2: '', // 回收说明内容
			data: {
				title: '',
				sales_price: '',
				label_arr: [],
				image: '',
				mountings: null, // 配件列表
				is_receive_other: 0, // 是否支持别家购买回收
				content: '',
				images: '',
				video_file: '',
				specList: '',
				specTableList: ''
			},
			specList: [], // 规格列表（解析后）
			specTableList: [], // 规格价格表（解析后）
			price1: '0', // 自家购买验货费
			price2: '0', // 别家购买验货费
			cart: [], // 购物车数据
			current: 0, // 轮播当前索引
			priceSums: 0, // 配件总扣减金额
			selectList: [], // 已选规格列表
			id: '' // 商品ID
		};
	},

	computed: {
		// 计算预计可获得金额（纯计算逻辑，不修改数据）
		total() {
			return (specList, specTableList, type) => {
				// 处理规格未选择的情况
				if (!specList.length || !specTableList.length) return '0.00';

				// 获取已选规格组合
				const selectedSpecs = specList.map((item) => item.child[item.sindex] || '');
				// 匹配对应规格的价格
				const targetSpec = specTableList.find((item) => item.value.toString() === selectedSpecs.toString());

				if (!targetSpec) return '0.00';

				// 计算配件扣减金额
				const mountingsDeduct = this.data.mountings ? this.data.mountings.filter((item) => item.active).reduce((prev, cur) => prev + Number(cur.intro || 0), 0) : 0;

				this.priceSums = mountingsDeduct;

				// 计算最终金额：规格价格 - 验货费 - 配件扣减
				const finalPrice = Number(targetSpec.sales_price || 0) - Number(type === 1 ? this.price1 : this.price2) - mountingsDeduct;

				return finalPrice.toFixed(2);
			};
		}
	},

	onLoad(options) {
		// 初始化导航栏样式
		my.setNavigationBar({
			frontColor: '#000',
			backgroundColor: '#fff'
		});

		this.id = options.id || '';
		// 初始化购物车（从缓存读取）
		this.cart = JSON.parse(uni.getStorageSync('cart') || '[]');

		// 未登录则跳转登录，登录成功后拉取数据
		if (!uni.getStorageSync('token')) {
			this.login().then(() => {
				this.initData(); // 登录成功后初始化数据
			});
		} else {
			this.initData(); // 已登录直接初始化数据
		}
	},

	methods: {
		// 初始化所有数据（统一入口）
		async initData() {
			try {
				// 并行请求：提升接口请求效率
				const [systemRes, productRes] = await Promise.all([this.$http.post('/api/index/systemConfig'), this.$http.post('/api/product/detail', { id: this.id })]);

				// 处理系统配置数据
				if (systemRes.code === 1) {
					this.content2 = systemRes.data.receive_info || '';
				} else {
					uni.showToast({ title: systemRes.msg || '系统配置获取失败', icon: 'none' });
				}

				// 处理商品详情数据
				if (productRes.code === 1) {
					this.handleProductData(productRes.data);
				} else {
					uni.showToast({ title: productRes.msg || '商品详情获取失败', icon: 'none' });
				}
			} catch (err) {
				console.error('数据初始化失败：', err);
				uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
			}
		},

		// 处理商品详情返回数据
		handleProductData(productData) {
			this.data = { ...this.data, ...productData };

			// 处理轮播图/视频数据
			this.handleBannerList(productData);

			// 处理配件数据（初始化active状态）
			if (productData.mountings) {
				this.data.mountings = JSON.parse(productData.mountings).map((item) => ({
					...item,
					active: false
				}));
			}

			// 处理规格数据
			this.handleSpecData(productData);

			// 初始化富文本内容
			this.content1 = productData.content || '';
		},

		// 处理轮播图/视频列表
		handleBannerList(productData) {
			const imageList = productData.images
				? productData.images.split(',').map((url) => ({
						url,
						type: 'image'
				  }))
				: [];

			// 视频优先展示（插入到列表首位）
			this.blist = productData.video_file ? [{ url: productData.video_file, type: 'video' }, ...imageList] : imageList;
		},

		// 处理规格和价格表数据
		handleSpecData(productData) {
			// 解析规格列表
			this.specList = productData.specList
				? JSON.parse(productData.specList).map((item) => ({
						...item,
						sindex: 0 // 默认选中第一个规格
				  }))
				: [];

			// 解析规格价格表
			this.specTableList = productData.specTableList ? JSON.parse(productData.specTableList) : [];

			// 初始化已选规格和价格
			this.selectList = this.specList.map((item) => item.child[0] || '');
			if (this.specTableList[0]) {
				this.price1 = this.specTableList[0].my_dec_price || '0';
				this.price2 = this.specTableList[0].ta_dec_price || '0';
			}
		},

		// 登录逻辑（返回Promise，支持异步等待）
		login() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'alipay',
					success: (loginRes) => {
						this.$http
							.post('/api/user/getAliUserIdByCode', {
								code: loginRes.authCode
							})
							.then((res) => {
								if (res.code === 1) {
									// 登录信息存入缓存
									uni.setStorageSync('token', res.data.userinfo.token);
									uni.setStorageSync('userId', res.data.userinfo.user_id);
									uni.setStorageSync('loginTime', new Date().getTime());
									uni.showToast({ title: '登录成功', icon: 'none', duration: 1500 });
									resolve();
								} else {
									uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
									reject(res.msg);
								}
							})
							.catch((err) => {
								console.error('登录接口请求失败：', err);
								reject(err);
							});
					},
					fail: (err) => {
						console.error('获取authCode失败：', err);
						uni.showToast({ title: '登录授权失败', icon: 'none' });
						reject(err);
					}
				});
			});
		},

		// 轮播切换事件
		swiperChange(e) {
			this.current = e.detail.current;
		},

		// 底部缩略图切换轮播
		scrollChange(index) {
			this.current = index;
		},

		// 分享面板展示
		showSharePanel() {
			my.showSharePanel();
		},

		// 分享配置
		onShareAppMessage() {
			return {
				title: this.data.title || '优质商品推荐',
				desc: this.data.label_arr.join('、') || '快来看看吧',
				path: `pages/index/goods?id=${this.id}`,
				success: (res) => console.log('分享成功：', res),
				fail: (res) => console.log('分享失败：', res)
			};
		},

		// 配件选择切换（多选）
		changMountings(item) {
			if (item) item.active = !item.active;
		},

		// 加入回收袋（提交购物车）
		submit() {
			// 校验配件选择（必选）
			if (this.data.mountings) {
				const selectedMountings = this.data.mountings.filter((item) => item.active);
				if (selectedMountings.length === 0) {
					uni.showToast({ title: '请选择配件', icon: 'none' });
					return;
				}
			}

			// 校验规格选择
			const selectedSpecs = this.specList.map((item) => item.child[item.sindex] || '');
			const targetSpec = this.specTableList.find((item) => item.value.toString() === selectedSpecs.toString());

			if (!targetSpec) {
				uni.showToast({ title: '请选择完整规格', icon: 'none' });
				return;
			}

			// 构造购物车数据
			const cartItem = {
				title: this.data.title,
				id: this.id,
				spec: selectedSpecs,
				price: targetSpec.sales_price || '0',
				mountings_price: this.priceSums,
				num: 1,
				mountings_text: this.data.mountings ? this.data.mountings.filter((item) => item.active) : [],
				type: this.type,
				deduct_price: this.type === 1 ? this.price1 : this.price2,
				image: this.data.image,
				my_dec_price: this.price1,
				ta_dec_price: this.price2
			};

			// 购物车去重（同一商品+同一规格+同一类型+同一配件组合）
			const existIndex = this.cart.findIndex(
				(item) =>
					item.id === this.id &&
					item.spec.toString() === selectedSpecs.toString() &&
					item.type === this.type &&
					this.isArrEqual3(item.mountings_text, cartItem.mountings_text)
			);

			if (existIndex > -1) {
				this.cart[existIndex].num++;
			} else {
				this.cart.push(cartItem);
			}

			// 存入缓存并跳转购物车
			uni.setStorageSync('cart', JSON.stringify(this.cart));
			uni.switchTab({ url: '/pages/index/cart' });
		},

		// 数组比较（判断配件选择是否一致）
		isArrEqual3(arr1, arr2) {
			if (!Array.isArray(arr1) || !Array.isArray(arr2)) return false;
			if (arr1.length !== arr2.length) return false;
			return arr1.toString() === arr2.toString();
		},

		// 规格切换
		navChange(item, specIndex, specValue, valueIndex) {
			// 更新已选规格索引和列表
			this.specList[specIndex].sindex = valueIndex;
			this.selectList[specIndex] = specValue;

			// 匹配对应规格的价格
			const targetSpec = this.specTableList.find((item) => item.value.join() === this.selectList.join());

			if (targetSpec) {
				this.price1 = targetSpec.my_dec_price || '0';
				this.price2 = targetSpec.ta_dec_price || '0';
			}

			this.$forceUpdate();
		},

		// 验货费类型切换
		changeType(type) {
			this.type = type;
		},

		// 弹窗打开
		open() {
			this.show = true;
		},

		// 弹窗关闭
		close() {
			this.show = false;
		}
	}
};
</script>

<style lang="less" scoped>
@color: #e31d21;

.container {
	padding-bottom: 120rpx;

	.pop-buy {
		padding: 30rpx 30rpx 0;
		height: 800rpx;
		display: flex;
		align-items: center;
		flex-direction: column;

		.title {
			height: 60rpx;
			line-height: 40rpx;
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
			padding-right: 40rpx;
		}

		.total {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			color: #333;
			text-align: left;
			font-size: 28rpx;

			text {
				color: @color;
				padding: 0 10rpx;
			}
		}

		.list {
			width: 100%;
			height: 1rpx;
			flex: 1;
			margin-top: 30rpx;

			.scroll-Y {
				width: 100%;
				height: 100%;
			}

			.item {
				margin-bottom: 20rpx;

				.t {
					height: 60rpx;
					line-height: 60rpx;
					font-size: 28rpx;
					color: #333;
					font-weight: 600;
				}

				.c {
					flex-wrap: wrap;

					.i {
						margin-top: 20rpx;
						width: calc(50% - 20rpx);
						line-height: 50rpx;
						border: 2rpx solid #eee;
						background-color: #f9f9f9;
						text-align: center;
						font-size: 24rpx;
						border-radius: 6rpx;
					}

					.on {
						border: 2rpx solid;
						background-color: #fef0f0;
						border-color: #fde2e2;
						color: #f56c6c !important;
					}
				}
			}
		}

		.btn {
			margin-top: 30rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			width: 50%;
			text-align: center;
			background-color: @color;
			color: #fff;
			font-size: 28rpx;
		}
	}

	.banner-bottom {
		width: 100%;
		height: 100rpx;

		.scroll-view_H {
			width: 100%;
			height: 100rpx;
			white-space: nowrap;

			.item {
				width: 25%;
				height: 100rpx;
				display: inline-flex;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.on {
				image {
					filter: blur(4rpx);
				}
			}
		}
	}

	.mian {
		padding: 20rpx 30rpx;
		background-color: #fff;
		margin-bottom: 30rpx;

		.title-price {
			.l {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
				line-height: 50rpx;
			}

			.r {
				font-size: 28rpx;
				color: @color;
				font-weight: 600;
			}
		}

		.tips {
			margin-top: 10rpx;
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			text {
				display: inline-flex;
				height: 30rpx;
				line-height: 30rpx;
				border: 2rpx solid #eee;
				border-radius: 6rpx;
				padding: 0 10rpx;
				font-size: 24rpx;
				color: #666;
				margin: 10rpx 10rpx 0 0;
			}
		}

		.title {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
			height: 60rpx;
			line-height: 60rpx;
		}

		.body {
			margin-top: 20rpx;
		}
	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 0 30rpx 0 40rpx;
		background-color: #fff;
		z-index: 999;
		height: 80rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.l {
			flex: 1;
			width: 1rpx;

			image {
				width: 40rpx;
				height: 40rpx;
				margin-left: 30rpx;
			}
		}

		.r {
			width: 180rpx;
			height: 60rpx;
			line-height: 60rpx;
			text-align: center;
			font-size: 28rpx;
			color: #fff;
			background-color: @color;
			border-radius: 30rpx;
		}
	}
}

.banner {
	width: 100%;
	height: 450rpx;
	overflow: hidden;

	.swiper {
		width: 100%;
		height: 100%;

		.swiper-item {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}

			video {
				width: 100%;
				height: 100%;
			}
		}
	}
}
</style>
